package com.starblink.product.detail.ui

import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewTreeObserver
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.appsflyer.AppsflyerManager
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.ext.inflater
import com.starblink.android.basic.ext.toBean
import com.starblink.android.basic.ext.toJson
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.CollectProductEvent
import com.starblink.android.basic.util.bus.bean.FollowStoreEvent
import com.starblink.android.basic.util.bus.bean.FollowUserEvent
import com.starblink.android.common.utils.PostDetailHelp
import com.starblink.basic.apollo.ext.ApolloValSetExt
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.view.behavior.PagerStartSnapHelper
import com.starblink.basic.style.view.round.CornerType
import com.starblink.basic.style.view.round.RoundKornerConstraintLayout
import com.starblink.basic.util.CommUtils
import com.starblink.basic.util.FilesUtils
import com.starblink.product.R
import com.starblink.product.controller.PostVideoController
import com.starblink.product.controller.VideoRenderViewFactory
import com.starblink.product.databinding.ActivityProductDetailBinding
import com.starblink.product.databinding.ItemRecommendPostDetailBinding
import com.starblink.product.databinding.ItemRecommendVideoDetail2Binding
import com.starblink.product.detail.adapter.ProductDetailCell
import com.starblink.product.detail.postrecommend.RecommendPostDetailHolder
import com.starblink.product.detail.postrecommend.VideoDetailHolder
import com.starblink.product.detail.postrecommend.data.PicPost
import com.starblink.rocketreserver.fragment.PostD
import com.starblink.rocketreserver.fragment.Poster
import com.starblink.rocketreserver.fragment.ProductD
import com.starblink.rocketreserver.fragment.ProductF
import com.starblink.rocketreserver.type.ProductCollectionStatusReq
import com.starblink.share.view.ShareDialog
import com.starblink.share.view.utils.ShareTypeEnum
import com.starblink.share.view.utils.ShareUrlUtils
import com.starblink.video.player.SingleVideoView
import com.starblink.video.player.VideoView
import com.starblink.video.util.VideoUtils
import com.starblink.videocache.cache.PreloadManager
import com.youth.banner.Banner

@Route(path = RoutePage.Product.PAGE_DETAIL)
class ProductDetailActivity :
    BaseTVMActivity<ActivityProductDetailBinding, ProductRecommendListVM>() {

    @Autowired(name = RoutePage.Product.PRODUCT_ID)
    @JvmField
    var productId: String = ""

    @Autowired(name = RoutePage.Product.TRACE_ID)
    @JvmField
    var traceId: String? = null

    @Autowired(name = RoutePage.Product.STANDARD_SPU_ID)
    @JvmField
    var standardSpuId: String = ""

    @Autowired(name = RoutePage.Product.POST_ID)
    @JvmField
    var postId: String? = null

    @Autowired(name = RoutePage.Product.MOUTED_PRODUCT_LIST)
    @JvmField
    var productList: String? = null

    var mountedProducts: List<ProductCollectionStatusReq>? = null//内容挂载商品

    @Autowired(name = RoutePage.Product.PRODUCT)
    @JvmField
    var product: ProductF? = null

    var currentIndex = 0//当前Index

    var mountedIsOpen = false//挂载商品弹窗是否打开
    var currentIsVideo = false//当前是否是视频
    var isMuteVideoMap: MutableMap<String, Boolean> = mutableMapOf()//当前视频是否静音

    lateinit var mPreloadManager: PreloadManager

    lateinit var layoutManager: LinearLayoutManager

    private lateinit var mController: PostVideoController

    lateinit var mVideoView: VideoView

    override fun initViewBinding(): ActivityProductDetailBinding =
        ActivityProductDetailBinding.inflate(layoutInflater)

    private val adapter: MutableAdapter by lazyOnNone {
        MutableAdapter(viewModel.resultList.value!!).apply {
            addVhDelegate {
                ProductDetailCell(
                    it,
                    mActivity as AppCompatActivity,
                    viewModel.resultList.value!!, traceId ?: "", pageTrackTag = this.hashCode().toString()
                )
            }
            addVhDelegate {
                RecommendPostDetailHolder(
                    ItemRecommendPostDetailBinding.inflate(it.inflater, it, false),
                    mActivity as AppCompatActivity,
                    viewModel.resultList.value!!,
                    pageTrackTag = this.hashCode().toString()
                ) {}
            }
            addVhDelegate {
                VideoDetailHolder(
                    ItemRecommendVideoDetail2Binding.inflate(it.inflater, it, false),
                    mActivity as AppCompatActivity,
                    isRecommend = true,
                    list = viewModel.resultList.value!!, pageTrackTag = this.hashCode().toString(),
                    spmPageValue = SpmPageDef.SimilarProductListPage,
                    onSearchPicClick = {
                        screenShot()
                    }, shareCallBack = { id ->
//                        viewModel.sharePost(id)
                    }, showMountedDialog = {
                        mountedIsOpen = true
                        mVideoView.pause()
                    }, dismissMountedDialog = {
                        mountedIsOpen = false
                        mVideoView.resume()
                    }, onMutedClick = { id, isMute ->
                        isMuteVideoMap[id] = isMute
                        mVideoView.isMute = isMute
                    }
                )
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setStatusBarBlackText()
        layoutManager = LinearLayoutManager(this)
        viewBinding.rv.layoutManager = layoutManager
        viewBinding.refresher.setEnableRefresh(false)
        viewBinding.refresher.setEnableLoadMore(false)
        viewBinding.refresher.setOnLoadMoreListener {
            viewModel.getRecommend2(productId, standardSpuId, postId, mountedProducts)
            viewBinding.refresher.finishLoadMore(5000)
        }
        if (postId?.isNotEmpty() == true && productList?.isNotEmpty() == true) {
            mountedProducts = PostDetailHelp.getShareProductList(productList!!)
        }
        initVideoView()

        viewModel.getRecommend2(
            productId,
            standardSpuId,
            postId,
            mountedProducts,
            showLoading = product == null
        )

        if (product != null) {
            viewModel.resultList.value = arrayListOf()
            viewModel.resultList.value?.add(product!!.toJson().toBean<ProductD>())
            viewModel.resultList.value = viewModel.resultList.value
        }

        viewModel.resultList.observe(this) {
            if (viewBinding.rv.adapter == null) {
                viewBinding.rv.adapter = adapter

                val snapHelper = PagerStartSnapHelper()
                snapHelper.attachToRecyclerView(viewBinding.rv)

                viewBinding.rv.viewTreeObserver.addOnGlobalLayoutListener(object :
                    ViewTreeObserver.OnGlobalLayoutListener {
                    override fun onGlobalLayout() {
                        //因为onGlobalLayout可能会多次调用，所以记得移除监听
                        val width = viewBinding.rv.width
                        val height = viewBinding.rv.height
                        //通过调用view.getHeight()和view.getWidth()来判断view是否已经绘制好
                        if (width > 0 && height > 0) {
                            viewBinding.rv.viewTreeObserver.removeOnGlobalLayoutListener(this)
                        } else {
                            return
                        }
                        startPlay(0)
                    }
                })
            }
            if (it.isNotEmpty()) {
                adapter.notifyDataSetChanged()
                if (it.size > 1) {
                    viewBinding.refresher.setEnableLoadMore(true)
                    viewBinding.bgH.visibleOrGone(false) {}
                }
            }
        }

        flowData()

        setListener(layoutManager)
    }

    private fun initVideoView() {
        mVideoView = VideoView(this)
        mVideoView.setLifecycle(lifecycle)
        mVideoView.setLooping(true)

        //以下只能二选一，看你的需求
        mVideoView.setRenderViewFactory(VideoRenderViewFactory.create())
//        mVideoView.setScreenScaleType(VideoView.SCREEN_SCALE_MATCH_PARENT);
        mController = PostVideoController(this)
        mVideoView.setVideoController(mController)
        mPreloadManager = PreloadManager.getInstance(this)
    }


    /**
     * 自动播放内容卡片视频
     */
    private fun autoPlayPostVideo(
        layoutManager: LinearLayoutManager,
        rv: RecyclerView,
        viewId: Int
    ) {
        rv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            private var mCurItem = 0

            /**
             * VerticalViewPager是否反向滑动
             */
            private var mIsReverseScroll = false
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    val position = layoutManager.findFirstVisibleItemPosition()

                    if (currentIndex == (viewModel.resultList.value?.size
                            ?: 0) - 2 && !viewModel.isLoading
                    ) {
                        viewModel.getRecommend2(productId, standardSpuId, postId, mountedProducts)
                    }

                    val view = layoutManager.findViewByPosition(position)
                    dealShareAction(position, view)

                    if (view?.findViewById<View>(R.id.banner) != null) {
                        val banner = view.findViewById<View>(R.id.banner) as Banner<*, *>?
//                        banner?.isAutoLoop(true)
                        banner?.setCurrentItem(banner.startPosition, false)
                        banner?.setIndicatorPageChange()
                    }

                    if (currentIndex < 3) {
                        viewBinding.llBottomGuide.visibleOrGone(true) {}
                    }
                } else {
                    viewBinding.llBottomGuide.visibleOrGone(false) {}
                }

                if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    mCurItem = layoutManager.findFirstVisibleItemPosition()
                }
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    mPreloadManager.resumePreload(currentIndex, mIsReverseScroll)
                } else {
                    mPreloadManager.pausePreload(currentIndex, mIsReverseScroll)
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val position = layoutManager.findFirstVisibleItemPosition()
                if (position == mCurItem) {
                    return
                }
                val lastPosition = layoutManager.findLastVisibleItemPosition()
                val view = layoutManager.findViewByPosition(lastPosition)
                view?.let { changeContainerRadius(it, true) }

                mVideoView.pause()
                mIsReverseScroll = position < mCurItem
            }
        })
    }

    /**
     * 处理不同类型more逻辑
     */
    private fun dealShareAction(position: Int, view: View?) {
        val data = view?.tag
        if (data != null) {
            changeContainerRadius(view)
            when (data) {
                is PostD -> {
                    setStatusBarWhiteText()
//                    viewBinding.ivShare.setImageResource(com.starblink.basic.style.R.mipmap.icon_detial_more)
                    viewBinding.ivShare.setOnClickListener {
                        shareVideoPost(data)
                    }

                    if (position == currentIndex) return
                    startPlay(position)
                }
                is PicPost -> {
                    currentIsVideo = false
                    currentIndex = position
                    setStatusBarBlackText()
//                    viewBinding.ivShare.setImageResource(com.starblink.basic.style.R.mipmap.icon_detial_more)
                    viewBinding.ivShare.setOnClickListener {
                        var productStr = PostDetailHelp.getShareProductListString(data.productList)
                        ShareDialog(
                            mActivity,
                            "${ShareUrlUtils().getUrl(ShareTypeEnum.PIC_POST)}${data.id}&type=1&productList=$productStr&countryCode=${UserDataCenter.getLocalCountryCode()}",
                            shareCome = ShareTypeEnum.PIC_POST
                        ) {
                        }.show(supportFragmentManager, "share")

                        AppsflyerManager.reportContentShare(
                            mapOf(
                                "af_content_id" to data.id,
                                "af_content_type" to (data.contentType ?: "1"),
                            )
                        )
                    }

                }
                is ProductD -> {
                    currentIsVideo = false
                    currentIndex = position
                    setStatusBarBlackText()
                    viewBinding.ivShare.setImageResource(com.starblink.basic.style.R.mipmap.icon_detail_share)
                    viewBinding.ivShare.setOnClickListener {
                        ShareDialog(
                            mActivity,
                            "${ShareUrlUtils().getUrl(ShareTypeEnum.PRODUCT)}&type=1&productId=${data.id}&standardSpuIds=${data.standardSpuIds}",
                            shareCome = ShareTypeEnum.PRODUCT, imageUrl = data?.mainImg
                        ) {
                        }.show(supportFragmentManager, "share")
                    }
                }
            }
        }
    }

    private fun shareVideoPost(data: PostD) {
        var productStr = PostDetailHelp.getShareProductListString(data.productList)
        ShareDialog(
            mActivity,
            "${ShareUrlUtils().getUrl(ShareTypeEnum.VIDEO_POST)}${data.id}&type=1&productList=$productStr&countryCode=${UserDataCenter.getLocalCountryCode()}",
            shareCome = ShareTypeEnum.VIDEO_POST, imageUrl = data.mainPic
        ) {
        }.show(supportFragmentManager, "share")

        AppsflyerManager.reportContentShare(
            mapOf(
                "af_content_id" to data.id,
                "af_content_type" to (data.contentType ?: "1"),
            )
        )
    }

    private fun changeContainerRadius(view: View, isScroll: Boolean = false) {
        if (view?.findViewById<View>(R.id.container) != null) {
            val container: RoundKornerConstraintLayout = view.findViewById(R.id.container)
            if (isScroll) {
                container.setCornerRadius(
                    CommUtils.dip2px(32f),
                    CornerType.TOP_LEFT,
                )
                container.setCornerRadius(
                    CommUtils.dip2px(32f),
                    CornerType.TOP_RIGHT,
                )
            } else {
                container.setCornerRadius(
                    0f,
                    CornerType.ALL,
                )
            }
        }
    }

    ///播放视频
    private fun startPlay(position: Int) {
        val itemView = layoutManager.findViewByPosition(position)
        if (itemView?.findViewById<View>(R.id.tiktok_View) != null) {
            val tiktokView: SingleVideoView = itemView.findViewById(R.id.tiktok_View)
            val tiktokBean = itemView.tag

            if (tiktokBean is PostD) {
                mVideoView.release()
                VideoUtils.removeViewFormParent(mVideoView)
                if (tiktokBean.pictures != null && tiktokBean.pictures!!.isNotEmpty()) {
                    val playUrl = mPreloadManager.getPlayUrl(
                        tiktokBean.pictures?.get(0)?.pictureF?.picUrl
                            ?: ""
                    )
                    mVideoView.setUrl(playUrl)
                    //请点进去看isDissociate的解释
                    mController.addControlComponent(tiktokView, true)
                    tiktokView.addView(mVideoView, 0)
                    Log.e(
                        "VideoDetailTVMActivity",
                        "===1111==${playUrl}"
                    )
                    val mute = isMuteVideoMap[tiktokBean.id] ?: true
                    mVideoView.isMute = mute
                    mVideoView.start()
                }
                currentIsVideo = true
                currentIndex = position
            }
        }
    }

    /**
     * 截图识图
     */
    private fun screenShot() {
        viewModel.resultList.value ?: return
        val played = mVideoView.currentPosition > 0
        val bitmap = mVideoView.doScreenShot()
        val index = if (currentIndex < viewModel.resultList.value!!.size) currentIndex else 0
        var post = viewModel.resultList.value!![index]
        if (post is PostD) {
            if (bitmap != null && played) {
                val path = FilesUtils.getInstance().saveBitmap(
                    bitmap,
                    "video_${post.id}_${System.currentTimeMillis()}"
                )
                this.navigationTo(RoutePage.ImageSearch.PAGE_RESULT) {
                    withString(RoutePage.ImageSearch.ARGS_FILE_PATH, path)
                }
            } else {
                this.navigationTo(RoutePage.ImageSearch.PAGE_RESULT) {
                    withString(
                        RoutePage.ImageSearch.ARGS_IMG_URL,
                        post.mainPic
                    )
                }
            }
        }
    }

    private fun flowData() {
        //同步订阅数据
        FlowBus.with<FollowStoreEvent>(FlowConst.FOLLOW_STORE_EVENT).register(this) { event ->
            for (index in viewModel.resultList.value?.indices!!) {
                val it = viewModel.resultList.value!![index]
                if (it is ProductD && it.merchantWeb != null && it.merchantWeb!!.id == event.id && event.followed != it.merchantWeb!!.subOrNot) {
                    val merchant = it.merchantWeb!!
                    ApolloValSetExt.setApolloVal<ProductD.MerchantWeb>(
                        merchant,
                        "subOrNot",
                        event.followed
                    )
                    viewModel.resultList.value!![index] = it
                    viewModel.resultList.value = viewModel.resultList.value
                    break
                }
            }
        }

        //同步收藏状态
        FlowBus.with<CollectProductEvent>(FlowConst.COLLECT_PRODUCT_EVENT).register(this) { event ->
            for (index in viewModel.resultList.value?.indices!!) {
                val it = viewModel.resultList.value!![index]
                if (it is ProductD && it.id == event.id && event.collect != it.collected) {
                    ApolloValSetExt.setApolloVal<ProductD>(
                        it,
                        "collected",
                        event.collect
                    )
                    Log.e("ProductDetailCardView", "===2222==${event.collect}")
                    viewModel.resultList.value!![index] = it
                    viewModel.resultList.value = viewModel.resultList.value
                }
            }
        }

        //同步关注状态
        FlowBus.with<FollowUserEvent>(FlowConst.FOLLOW_USER_EVENT).register(this) { event ->
            for (index in viewModel.resultList.value?.indices!!) {
                val it = viewModel.resultList.value!![index]
                changeFollowState(it, event, index)
                if (it is PostD && it.posterInfo.poster != null && it.posterInfo.poster.id == event.id
                    && event.relationCode != it.posterInfo.poster.relationCode
                ) {
                    val poster = it.posterInfo.poster
                    ApolloValSetExt.setApolloVal<Poster>(
                        poster,
                        "relationCode",
                        event.relationCode
                    )
                    viewModel.resultList.value!![index] = it
                    viewModel.resultList.value = viewModel.resultList.value
                }
            }
        }

        //同步挂载商品订阅数据
        FlowBus.with<FollowStoreEvent>(FlowConst.FOLLOW_STORE_EVENT).register(this) { event ->
            for (index in viewModel.resultList.value?.indices!!) {
                val post = viewModel.resultList.value!![index]
                if (post is PicPost) {
                    val productList = post.productList
                    followStore(productList, event, index, post)
                }
                if (post is PostD) {
                    val productList = post.productList
                    followStore(productList, event, index, post)
                }
            }
        }

        //同步挂载商品收藏状态
        FlowBus.with<CollectProductEvent>(FlowConst.COLLECT_PRODUCT_EVENT).register(this) { event ->
            for (index in viewModel.resultList.value?.indices!!) {
                val post = viewModel.resultList.value!![index]
                if (post is PicPost) {
                    val productList = post.productList
                    collectProduct(productList, event, index, post)
                }
                if (post is PostD) {
                    val productList = post.productList
                    collectProduct(productList, event, index, post)
                }
            }
        }
    }

    private fun collectProduct(
        productList: List<PostD.ProductList1>?,
        event: CollectProductEvent,
        index: Int,
        post: Any
    ) {
        if (productList != null && productList.isNotEmpty()) {
            for (item in productList) {
                var it = item.productF
                if (it.id == event.id && event.collect != it.collected) {
                    ApolloValSetExt.setApolloVal<ProductF>(
                        it,
                        "collected",
                        event.collect
                    )
                    viewModel.resultList.value!![index] = post
                    viewModel.resultList.value = viewModel.resultList.value
                    break
                }
            }
        }
    }

    private fun followStore(
        productList: List<PostD.ProductList1>?,
        event: FollowStoreEvent,
        index: Int,
        post: Any
    ) {
        if (productList != null && productList.isNotEmpty()) {
            for (item in productList) {
                var it = item.productF
                if (it.merchantWeb != null && it.merchantWeb!!.id == event.id && event.followed != it.merchantWeb!!.subOrNot) {
                    val merchant = it.merchantWeb!!
                    ApolloValSetExt.setApolloVal<ProductF.MerchantWeb>(
                        merchant,
                        "subOrNot",
                        event.followed
                    )
                    viewModel.resultList.value!![index] = post
                    viewModel.resultList.value = viewModel.resultList.value
                    break
                }
            }
        }
    }

    private fun changeFollowState(
        it: Any,
        event: FollowUserEvent,
        index: Int
    ) {
        if (it is PicPost && it.posterInfo.poster != null && it.posterInfo.poster.id == event.id
            && event.relationCode != it.posterInfo.poster.relationCode
        ) {
//            Log.d("VideoDetailVM", "----${event}")
            val poster = it.posterInfo.poster
            ApolloValSetExt.setApolloVal<Poster>(
                poster,
                "relationCode",
                event.relationCode
            )
            viewModel.resultList.value!![index] = it
            viewModel.resultList.value = viewModel.resultList.value
        }
    }

    private fun setListener(layoutManager: LinearLayoutManager) {
        viewBinding.ivSearch.setOnClickListener {
            com.starblink.android.basic.extension.navigationTo(RoutePage.Search.PAGE_SEARCH) {}
        }
        viewBinding.ivSearch.trackData(
            page = SpmPageDef.SimilarProductListPage,
            element = SpmElementDef.DiscoverSearch,
            onlyHit = true
        )

        viewBinding.ivBack.setOnClickListener {
            mActivity.finish()
        }        //检测recylerview的滚动事件

        autoPlayPostVideo(layoutManager, viewBinding.rv, R.id.video_player)

        viewBinding.ivShare.setOnClickListener {
            ShareDialog(
                mActivity,
                "${ShareUrlUtils().getUrl(ShareTypeEnum.PRODUCT)}&type=1&productId=${productId}&standardSpuIds=${standardSpuId}",
                shareCome = ShareTypeEnum.PRODUCT, imageUrl = product?.mainImg
            ) {
            }.show(supportFragmentManager, "share")
        }
    }

    override fun onResume() {
        super.onResume()
        pageExposure(SpmPageDef.SimilarProductListPage, params = mapOf("productId" to productId))

        if (mVideoView != null && !mountedIsOpen && currentIsVideo) {
            mVideoView.resume()
        }
    }

    override fun onPause() {
        pageDisappear(SpmPageDef.SimilarProductListPage, params = mapOf("productId" to productId))
        super.onPause()
        if (mVideoView != null) {
            mVideoView.pause()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mVideoView != null) {
            mVideoView.release()
        }
        mPreloadManager.removeAllPreloadTask()
    }
}